package com.caiyi.financial.nirvana.sms.service;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.cache.BlackMobileCache;
import com.caiyi.financial.nirvana.sms.entity.SmsBlacklist;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SubscribeEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.mapper.SmsBlacklistMapper;
import com.caiyi.financial.nirvana.sms.querybean.PageBean;
import com.caiyi.financial.nirvana.sms.querybean.QueryBlacklistBean;
import com.caiyi.financial.nirvana.sms.querybean.SendParamsQueryBean;
import com.caiyi.financial.nirvana.sms.querybean.SubmitBlackPhoneQueryBean;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.github.pagehelper.PageHelper;
import com.youyu.common.utils.YyAssert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SmsBlacklistService extends BaseService<SmsBlacklist> {

    @Autowired
    private SmsBlacklistMapper smsBlacklistMapper;

    public int addBlacklist(SmsBlacklist smsBlacklist) {
        YyAssert.isFalse(isExistBlacklist(smsBlacklist.getPhone()), ReturnCodeEnum.FAILED.code, "黑名单已经存在");
        int insertCount = this.insertByEntitySelective(smsBlacklist);
        //redis添加黑名单
        JedisService.sadd(JedisKey.SMS_BLACKLIST, smsBlacklist.getPhone());
        Map map = new HashMap();
        map.put("method", SubscribeEnum.ADDSYSMOBILE.method);
        map.put("phone", smsBlacklist.getPhone());
        JedisService.publish(JedisKey.SMS_SUBSCRIBE_API_ACTION, JSON.toJSONString(map));
        BlackMobileCache.addSysMobile(smsBlacklist.getPhone());
        return insertCount;
    }

    public boolean isExistBlacklist(String phone) {
        int count = smsBlacklistMapper.selectBlacklist(phone);
        return count > 0;
    }

    public int deleteBlacklist(Integer id) {
        SmsBlacklist smsBlacklist = new SmsBlacklist();
        smsBlacklist.setId(id);
        smsBlacklist = this.selectByPrimaryKey(smsBlacklist);
        int deleteCount = this.deleteByPrimaryKey(smsBlacklist);
        //redis中删除blacklist
        JedisService.srem(JedisKey.SMS_BLACKLIST, smsBlacklist.getPhone());
        Map map = new HashMap();
        map.put("method", SubscribeEnum.DELSYSMOBILE.method);
        map.put("phone", smsBlacklist.getPhone());
        BlackMobileCache.delSysMobile(smsBlacklist.getPhone());
        JedisService.publish(JedisKey.SMS_SUBSCRIBE_API_ACTION, JSON.toJSONString(map));
        return deleteCount;
    }

    public int updateBlacklist(SmsBlacklist smsBlacklist) {
        //删除redis中原来blacklist
        SmsBlacklist blacklist = new SmsBlacklist();
        blacklist.setId(smsBlacklist.getId());
        blacklist = this.selectByPrimaryKey(blacklist);
        JedisService.srem(JedisKey.SMS_BLACKLIST, blacklist.getPhone());
        smsBlacklist.setUpdateTime(new Date());
        int updateCount = this.updateByEntitySelective(smsBlacklist);
        //redis中更新blacklist
        JedisService.sadd(JedisKey.SMS_BLACKLIST, smsBlacklist.getPhone());
        BlackMobileCache.addSysMobile(smsBlacklist.getPhone());
        logger.info("updateByBlacklistId id {}", smsBlacklist.getId());
        return updateCount;
    }


    public PageBean<SmsBlacklist> getBlacklistByParams(QueryBlacklistBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsBlacklist> list = smsBlacklistMapper.selectBlacklistListByParams(bean);
        PageBean<SmsBlacklist> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public SubmitBlackPhoneQueryBean importBlackPhone(Set<String> phones) {
        String phoneStr = "";
        int phonesSize = 0;
        StringBuilder phoneBuilder = new StringBuilder();
        if (phones.size() > 10000) {
            logger.error("blackPhoneSize:{}", phones.size());
            YyAssert.isFalse(true, ReturnCodeEnum.PARAMS_ERROR.code, "号码数量不能大于10000");
        }
        if (phones.size() == 0) {
            logger.error("blackPhoneSize:{}", phones.size());
            YyAssert.isFalse(true, ReturnCodeEnum.PARAMS_ERROR.code, "号码数量不能等于0");
        }
        for (String phone : phones) {
            int operator = CommUtil.getPhoneOperator(phone);
            if (operator == 0) {
                continue;
            }
            phoneBuilder.append(phone + ",");
            phonesSize++;
        }
        if (StringUtils.isNotBlank(phoneBuilder.toString())) {
            phoneStr = phoneBuilder.deleteCharAt(phoneBuilder.length() - 1).toString();
        }
        YyAssert.isFalse(phonesSize == 0, ReturnCodeEnum.PARAMS_ERROR.code, "手机号码格式不正确");
        return new SubmitBlackPhoneQueryBean(phonesSize, phoneStr);
    }

    public int submitBlackPhone(SendParamsQueryBean sendParamsQueryBean) {
        List<SmsBlacklist> smsBlacklist = new ArrayList<>();
        String importPhone = sendParamsQueryBean.getPhones();
        String[] strPhones = importPhone.split(",");
        List<String> phoneList = Arrays.asList(strPhones);
        for (int i = 0; i < phoneList.size(); i++) {
            SmsBlacklist smsBlacklist1 = new SmsBlacklist();
            smsBlacklist1.setPhone(phoneList.get(i));
            smsBlacklist1.setUpdateTime(new Date());
            smsBlacklist1.setCreateTime(new Date());
            smsBlacklist.add(smsBlacklist1);
            strPhones[i] = phoneList.get(i);
        }
        int count = smsBlacklistMapper.insertList(smsBlacklist);
        JedisService.sadd(JedisKey.SMS_BLACKLIST, strPhones);
        BlackMobileCache.sysBlackSet.addAll(phoneList);
        //发布
        Map map = new HashMap();
        map.put("method", SubscribeEnum.ADDSYSLISTMOBILE.method);
        map.put("phones", strPhones);
        JedisService.publish(JedisKey.SMS_SUBSCRIBE_API_ACTION, JSON.toJSONString(map));
        return count;
    }
}
